package info.ask4research.web;

import info.ask4research.model.FileUploadBean;
import info.ask4research.model.Graph;
import info.ask4research.model.UnitOfLearning;
import info.ask4research.model.activities.Activity;
import info.ask4research.model.activities.LearningActivity;
import info.ask4research.model.activities.OneToTwoActivity;
import info.ask4research.model.activities.SupportActivity;
import info.ask4research.model.addons.Addon;
import info.ask4research.model.enums.FinishingActivity;
import info.ask4research.model.enums.ResourceType;
import info.ask4research.model.roles.Role;
import info.ask4research.model.toolsAndMaterials.AnnouncementService;
import info.ask4research.model.toolsAndMaterials.ChatService;
import info.ask4research.model.toolsAndMaterials.ForumService;
import info.ask4research.model.toolsAndMaterials.LearningObject;
import info.ask4research.model.toolsAndMaterials.SentMailService;
import info.ask4research.model.toolsAndMaterials.ToolAndMaterial;
import info.ask4research.service.IActivityService;
import info.ask4research.service.IAddonService;
import info.ask4research.service.IFileUploadBeanService;
import info.ask4research.service.IGraphService;
import info.ask4research.service.IRoleService;
import info.ask4research.service.IToolAndMaterialService;
import info.ask4research.service.IUnitOfLearningService;
import info.ask4research.web.validator.LearningDesignValidator;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;


@Controller
public class LearningDesignController {

	Document doc;
	private IActivityService activityService;
	private IUnitOfLearningService unitOfLearningService;
	private IFileUploadBeanService fileUploadBeanService;
	private IGraphService graphService;
	private IRoleService roleService;
	private IAddonService addonService;
	private IToolAndMaterialService toolAndMaterialService;
	private List<String> orderedList = new ArrayList<String>();
	HashMap<Object,Object> serial = new HashMap<Object,Object>();
	
	private HashMap<String,String> roles = new HashMap<String,String>();
	private HashMap<String,String> fileIds = new HashMap<String,String>();
	private HashMap<Integer,String> structureIds = new HashMap<Integer,String>();
	private HashMap<String,String> tamsIds = new HashMap<String,String>();
	private HashMap<String,String> actLearningIds = new HashMap<String,String>();
	private HashMap<String,String> actSupportIds = new HashMap<String,String>();
	private HashMap<FileUploadBean,String> filesIds = new HashMap<FileUploadBean,String>();
	private int countSplits = 0;
	
	@RequestMapping(value="jsp/learningDesign/validate.action")
	public @ResponseBody Map register(
			@RequestParam(value="htmlCode") String htmlCode,
			HttpSession session,HttpServletRequest request,
			HttpServletResponse response)  throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		boolean validated = false;
		String validationRules = "";
		if(unitOfLearning != null && !unitOfLearning.getActivity().isEmpty()){
			validated = false;
			List<Activity> activities = unitOfLearning.getActivity();
			for(Activity activity : activities){
				if(!(activity instanceof OneToTwoActivity)){
				List<FileUploadBean> files = activity.getFiles();
				if(files.isEmpty()){
					validated = false;
					validationRules += "Please add resources to your activity(ies)<br/>"; 
				} else {
					for(FileUploadBean fileUploadBean : files){
						if(fileUploadBean.getResourceType().equals(ResourceType.LADESCRIPTION) || 
								fileUploadBean.getResourceType().equals(ResourceType.SADESCRIPTION) ||
										!"".equals(activity.getDescription())){
							validated = true;
						}else{
							validated = false;
							validationRules += "Please add description(s) to your activity(ies)<br/>"; 
						}
					}
				}
				
				if(activity.getAuthor()!=null){
					validated = true;
				}else{
					validated = false;
					validationRules += "Please add author(s) to your activity(ies)<br/>"; 
				}
				//if(!activity.getAddons().isEmpty()){
				//	validated = true;
				//}else{
				//	validated = false;
				//	validationRules += "Please add Add-on(s) to your activity(ies)<br/>"; 
				//}
				if(!activity.getTams().isEmpty()){
					validated = true;
					List<ToolAndMaterial> listTams = activity.getTams();
					for(ToolAndMaterial tam : listTams){
						if(!(tam instanceof SentMailService)){
							if(!"".equals(tam.getDescription())){
								validated = true;
							}else{
								validated = false;
								validationRules += "Please add description(s) to your ToolAndMaterial(s)<br/>"; 
							}
						}
					}
				}else{
					validated = false;
					validationRules += "Please add Tools and Materials to your activity(ies)<br/>"; 
				}
				
			}
			}
		}
		validationRules+=analyzeAndOrderGraph(unitOfLearning.getGraph());
		if("".equals(validationRules)){
			modelMap.put("total", 0);
			modelMap.put("data", null);
			modelMap.put("success", true);
		}else{
			modelMap.put("total", 0);
			modelMap.put("data", validationRules);
			modelMap.put("failure", true);
		}
			
		return modelMap;
	}
	
	private String analyzeAndOrderGraph(Graph graph) throws ParserConfigurationException, Exception, IOException {
		LearningDesignValidator ldv = new LearningDesignValidator();
		return ldv.analiseStructure(graph.getGraphHtml());
	}
	
	
	@RequestMapping(value="jsp/learningDesign/export.action")
	public @ResponseBody void exportLD(
			HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));
		
		List<Activity> activities = unitOfLearning.getActivity();
		List<FileUploadBean> activityFiles = new ArrayList<FileUploadBean>();

		List<SupportActivity> supportActivities = new ArrayList<SupportActivity>();
		List<LearningActivity> learningActivities = new ArrayList<LearningActivity>();

		List<FileUploadBean> fileSupportActivities = new ArrayList<FileUploadBean>();
		List<FileUploadBean> fileLearningActivities = new ArrayList<FileUploadBean>();

		for(Activity activity : activities){
			activityFiles.addAll(activity.getFiles());
		}
		if(!activityFiles.isEmpty()){
			
			//ByteArrayInputStream byteArrayInputStream = createXMLInputStream(unitOfLearning);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ZipOutputStream zos = new ZipOutputStream(baos);
			
			ZipEntry entry = new ZipEntry("imsmanifest.xml");
			byte[] b = inputStream2bytes(createXMLInputStream(unitOfLearning));
			entry.setSize(b.length);
			//filesIds.clear();
			fileIds.clear();
			zos.putNextEntry(entry);
			zos.write(b);
			
			for(FileUploadBean file : activityFiles){
				ZipEntry entry1 = new ZipEntry(file.getName());
				entry1.setSize(file.getBytes().length);
				zos.putNextEntry(entry1);
				zos.write(file.getBytes());
			}
			if(!filesIds.isEmpty()){
				Set<FileUploadBean> files = filesIds.keySet();
				if(files.size()>0){
					for(FileUploadBean fileUploadBean : files){
						ZipEntry entry1 = new ZipEntry(fileUploadBean.getName());
						entry1.setSize(fileUploadBean.getBytes().length);
						zos.putNextEntry(entry1);
						zos.write(fileUploadBean.getBytes());
					}
					filesIds.clear();
					fileIds.clear();
				}
				
			}
			
			
			zos.closeEntry();
			zos.close();
			String fileName = unitOfLearning.getTitle()+".zip";
			InputStream is = new ByteArrayInputStream(baos.toByteArray());
			response.setContentType("application");
			response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
			response.setContentLength(is.available());
			response.getOutputStream().write( inputStream2bytes(is) );
		}

	}


	private byte[] inputStream2bytes(InputStream inStream) throws IOException {
		int fileSize = inStream.available();
		byte[] buffer = new byte[fileSize];
		inStream.read(buffer);
		return buffer;
	}
	
	public ByteArrayInputStream createXMLInputStream(UnitOfLearning uol) throws Exception{
		ByteArrayInputStream inputStream = null;
		LearningDesignValidator ldv = new LearningDesignValidator();
		
		serial = ldv.getStructure(uol.getGraph().getGraphHtml());
		
		try{
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		
		// root elements
		doc = docBuilder.newDocument();
		Element manifest = doc.createElement("manifest");
		doc.appendChild(manifest);
		SecureRandom random = new SecureRandom();

		String bi = new BigInteger(130, random).toString(32);
		createAttribute(manifest, "xmlns", "http://www.imsglobal.org/xsd/imscp_v1p1");
		createAttribute(manifest, "xmlns:imsld", "http://www.imsglobal.org/xsd/imsld_v1p0");
		createAttribute(manifest, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
		
		createAttribute(manifest, "xmlns:ldauthor", "http://www.ask4research.info/");
		createAttribute(manifest, "xsi:schemaLocation", "http://www.imsglobal.org/xsd/imscp_v1p1 http://www.imsglobal.org/xsd/imscp_v1p1.xsd http://www.imsglobal.org/xsd/imsld_v1p0 http://www.imsglobal.org/xsd/IMS_LD_Level_B.xsd");
		createAttribute(manifest, "identifier", "manifest-"+bi);
		
		Element metadata = doc.createElement("metadata");
		manifest.appendChild(metadata);
		Element lom = doc.createElement("lom");
		metadata.appendChild(lom);
		createAttribute(lom, "xmlns", "http://www.imsglobal.org/xsd/imsmd_v1p2");
		Element general = doc.createElement("general");
		lom.appendChild(general);
		Element title = doc.createElement("title");
		general.appendChild(title);
		createElementwithAttribute(title, "langstring", uol.getTitle());
		
		Element description = doc.createElement("description");
		general.appendChild(description);
		createElementwithAttribute(description, "langstring", uol.getDescription());
		
		// staff elements
		Element organizations = doc.createElement("imscp:organizations");
		manifest.appendChild(organizations);
		createAttribute(organizations, "xmlns:imscp", "http://www.imsglobal.org/xsd/imscp_v1p1");
		
		Element imsldlearning_design = doc.createElement("imsld:learning-design");
		organizations.appendChild(imsldlearning_design);
		
		createAttribute(imsldlearning_design, "identifier", bi);
		
		createAttribute(imsldlearning_design, "version", "1.0.0");
		createAttribute(imsldlearning_design, "level", "B");
		createAttribute(imsldlearning_design, "uri", "http://www.ask4research.info/"+bi);
		createAttribute(imsldlearning_design, "sequence-used", "false");
		
		createElementwithAttribute(imsldlearning_design, "imsld:title", uol.getTitle());
 
		Element imsldcomponents = doc.createElement("imsld:components");
		imsldlearning_design.appendChild(imsldcomponents);
		
		createRolesXML(imsldcomponents, uol);
		
		///////////////////////////////////////////////////////////////////////////////
		//START addons
		///////////////////////////////////////////////////////////////////////////////
		
		//createAddonXML(imsldcomponents, uol);
		
		///////////////////////////////////////////////////////////////////////////////
		//End addons
		///////////////////////////////////////////////////////////////////////////////
		
		///////////////////////////////////////////////////////////////////////////////
		//Activities start
		///////////////////////////////////////////////////////////////////////////////
		
		Element imsldactivities = doc.createElement("imsld:activities");
		imsldcomponents.appendChild(imsldactivities);
		
		///////////////////////////////////////////////////////////////////////////////
		//Learning Activities start
		///////////////////////////////////////////////////////////////////////////////

		
		createLearningActivityXML(imsldactivities, uol);
		
		///////////////////////////////////////////////////////////////////////////////
		//Learning Activities stop
		///////////////////////////////////////////////////////////////////////////////
	
		///////////////////////////////////////////////////////////////////////////////
		//Support Activities start
		///////////////////////////////////////////////////////////////////////////////

		
		
		createSupportActivityXML(imsldactivities, uol);
		
		
		createActivityStructure(imsldactivities, uol, serial);
		///////////////////////////////////////////////////////////////////////////////
		//Support Activities end
		///////////////////////////////////////////////////////////////////////////////

		///////////////////////////////////////////////////////////////////////////////
		//Activities end
		///////////////////////////////////////////////////////////////////////////////

		///////////////////////////////////////////////////////////////////////////////
		//Environments start - Tools and Materials
		///////////////////////////////////////////////////////////////////////////////
		
		Element imsldenvironments = doc.createElement("imsld:environments");
		imsldcomponents.appendChild(imsldenvironments);
		
		
		
		
		
		///////////////////////////////////////////////////////////////////////////////
		//Start - Learning Object Tools and Materials
		///////////////////////////////////////////////////////////////////////////////
		createLOEnvironment(imsldenvironments, uol);
		
		///////////////////////////////////////////////////////////////////////////////
		//End - Learning Object Tools and Materials
		///////////////////////////////////////////////////////////////////////////////
		
		///////////////////////////////////////////////////////////////////////////////
		//Start - Forum Service Tools and Materials
		///////////////////////////////////////////////////////////////////////////////
		
		createFSEnvironment(imsldenvironments, uol);
		
		createCSEnvironment(imsldenvironments, uol);
		
		createAnnounsementSEnvironment(imsldenvironments, uol);
		
		createSentMailEnvirnment(imsldenvironments, uol);
		
		
		createMethodEnvirnment(imsldlearning_design, uol);
		///////////////////////////////////////////////////////////////////////////////
		//End - Forum Service Tools and Materials
		///////////////////////////////////////////////////////////////////////////////
		
		///////////////////////////////////////////////////////////////////////////////
		//Environments stop - Tools and Materials
		///////////////////////////////////////////////////////////////////////////////
		Element resources = doc.createElement("imscp:resources");
		manifest.appendChild(resources);
		createAttribute(resources, "xmlns:imscp", "http://www.imsglobal.org/xsd/imscp_v1p1");
		
		createResources(resources, uol);
		
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		//initialize StreamResult with File object to save to file
		StreamResult result = new StreamResult(new StringWriter());
		DOMSource source = new DOMSource(doc);
		transformer.transform(source, result);
		String xmlString = result.getWriter().toString();
		
		TransformerFactory.newInstance().newTransformer().transform(source, result);
		
		inputStream = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));  
		System.out.println("File saved!");
	 } catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		  } catch (TransformerException tfe) {
			tfe.printStackTrace();
		  } catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return inputStream;
	}



	private void createMethodEnvirnment(Element imsldenvironments,
			UnitOfLearning uol) {

		Element imsld_method = doc.createElement("imsld:method");
		imsldenvironments.appendChild(imsld_method);
		
		createPlay(imsld_method, uol);
	}


	private void createPlay(Element imsld_method, UnitOfLearning uol) {

		
			
				SecureRandom random = new SecureRandom();
				Element imsld_play = doc.createElement("imsld:play");
				imsld_method.appendChild(imsld_play);
				createAttribute(imsld_play, "identifier", "play-"+new BigInteger(130, random).toString(32));
				createAttribute(imsld_play, "isvisible", "true");
				createElementwithAttribute(imsld_play, "imsld:title", uol.getTitle());
				//List<Activity> acts = uol.getActivity();
				
				List<Activity> orderActivities = new ArrayList<Activity>();
				int cnt = 0;
				for(int g=1 ; g< orderedList.size()-1; g++){
					if(!orderedList.get(g).contains(":")){
						Activity act = activityService.getbyGraphId(orderedList.get(g));
						if(act instanceof LearningActivity || act instanceof SupportActivity){
							Element imsld_act = doc.createElement("imsld:act");
							imsld_play.appendChild(imsld_act);
							createAttribute(imsld_act, "identifier", "act-"+new BigInteger(130, random).toString(32));
							createElementwithAttribute(imsld_act, "imsld:title", "act Title"+g);//TODO add title to activity
							Element imsld_rolepart = doc.createElement("imsld:role-part");
							imsld_act.appendChild(imsld_rolepart);
							createAttribute(imsld_rolepart, "identifier", "play-"+new BigInteger(130, random).toString(32));
							createElementwithAttribute(imsld_rolepart, "imsld:title", "act Title"+g);
							Element imsld_roleref = doc.createElement("imsld:role-ref");
							imsld_rolepart.appendChild(imsld_roleref);
							createAttribute(imsld_roleref, "ref", "role-"+roles.get(act.getAuthor().getText()));
							if(act instanceof LearningActivity){
								Element imsld_learningactivityref = doc.createElement("imsld:learning-activity-ref");
								imsld_rolepart.appendChild(imsld_learningactivityref);
								createAttribute(imsld_learningactivityref, "ref", actLearningIds.get(act.getActivityGraphId()));
						    } else if(act instanceof SupportActivity){
						    	Element imsld_learningactivityref = doc.createElement("imsld:support-activity-ref");
								imsld_rolepart.appendChild(imsld_learningactivityref);
								createAttribute(imsld_learningactivityref, "ref", actSupportIds.get(act.getActivityGraphId()));
						    }
						}
						
					}else{
						String[] actIdss = orderedList.get(g).split(":");
						Activity act = activityService.getbyGraphId(actIdss[0]);
						Element imsld_act = doc.createElement("imsld:act");
						imsld_play.appendChild(imsld_act);
						createAttribute(imsld_act, "identifier", "act-"+new BigInteger(130, random).toString(32));
						createElementwithAttribute(imsld_act, "imsld:title", "act Title"+g);//TODO add title to activity
						Element imsld_rolepart = doc.createElement("imsld:role-part");
						imsld_act.appendChild(imsld_rolepart);
						createAttribute(imsld_rolepart, "identifier", "play-"+new BigInteger(130, random).toString(32));
						createElementwithAttribute(imsld_rolepart, "imsld:title", "act Title"+g);
						Element imsld_roleref = doc.createElement("imsld:role-ref");
						imsld_rolepart.appendChild(imsld_roleref);
						createAttribute(imsld_roleref, "ref", "role-"+roles.get(act.getAuthor().getText()));
						Element imsld_learningactivityref = doc.createElement("imsld:learning-activity-ref");
						imsld_rolepart.appendChild(imsld_learningactivityref);
						createAttribute(imsld_learningactivityref, "ref", "as-"+structureIds.get(cnt++));
					}
						
				}
				orderedList.clear();	
	}

	private void createActivityStructure(Element imsldactivities,
			UnitOfLearning uol, HashMap<Object, Object> serial) {
		boolean containsSplit = (Boolean) serial.get("containsSplit");
		orderedList = (List<String>) serial.get("data");
		
		SecureRandom random = new SecureRandom();
		if(containsSplit){
			for(int i = 0; i<orderedList.size(); i++){
				if(orderedList.get(i).contains(":")){
					countSplits++;
				}
			}
			for(int j=0; j<countSplits;j++){
				
					Element imsld_activitystructure = doc.createElement("imsld:activity-structure");
					imsldactivities.appendChild(imsld_activitystructure);
					String bi = new BigInteger(130, random).toString(32);
					createAttribute(imsld_activitystructure, "identifier", "as-"+bi);
					structureIds.put(j, bi);
					createAttribute(imsld_activitystructure, "number-to-select", "0");
					createAttribute(imsld_activitystructure, "structure-type", "selection");
					createElementwithAttribute(imsld_activitystructure, "imsld:title", "Selection Point");
					
					for(int k = 0; k<orderedList.size(); k++){
						String id = orderedList.get(k);
						if(id.contains(":")){
							String[] selectionActivities = id.split(":");
							for(int f = 0; f<selectionActivities.length; f++){
								if(actLearningIds.containsKey(selectionActivities[f])){
									Element imsld_learningactivityref = doc.createElement("imsld:learning-activity-ref");
									imsld_activitystructure.appendChild(imsld_learningactivityref);
									createAttribute(imsld_learningactivityref, "ref", actLearningIds.get(selectionActivities[f]));
														
								}else if(actSupportIds.containsKey(selectionActivities[f])){
									Element imsld_supportactivityref = doc.createElement("imsld:support-activity-ref");
									imsld_activitystructure.appendChild(imsld_supportactivityref);
									createAttribute(imsld_supportactivityref, "ref", actSupportIds.get(selectionActivities[f]));
									
								}
							}
						}
					}
					
			}
		}
		
	}

	private void createResources(Element resources, UnitOfLearning uol) {
		Set<String> keys = fileIds.keySet();
		for(String key: keys){
			Element resource = doc.createElement("imscp:resource");
			resources.appendChild(resource);
			createAttribute(resource, "identifier", key);
			createAttribute(resource, "type", "webcontent");
			createAttribute(resource, "href", fileIds.get(key));
			
			Element file = doc.createElement("imscp:file");
			resource.appendChild(file);
			createAttribute(file, "href", fileIds.get(key));
		}
		
		Set<FileUploadBean> files = filesIds.keySet();
		
		for(FileUploadBean key: files){
			Element resource = doc.createElement("imscp:resource");
			resources.appendChild(resource);
			createAttribute(resource, "identifier", filesIds.get(key));
			createAttribute(resource, "type", "imsldcontent");
			createAttribute(resource, "href", key.getName());
			
			Element file = doc.createElement("imscp:file");
			resource.appendChild(file);
			createAttribute(file, "href", key.getName());
		}
		
		
	}


	private void createSentMailEnvirnment(Element imsldenvironments,UnitOfLearning uol) {
		List<SentMailService> sentMailServices = toolAndMaterialService.getSentMailServiceByUoL(uol.getId());
		SecureRandom random = new SecureRandom();
		for(SentMailService sm : sentMailServices){
			if(!tamsIds.containsKey(sm.getTitle())){
				String bi = new BigInteger(130, random).toString(32);
				tamsIds.put(sm.getTitle(), bi);
			}
		}
		for(SentMailService sm : sentMailServices){
			Element imsldenvironments_environement_SM = doc.createElement("imsld:environment");
			imsldenvironments.appendChild(imsldenvironments_environement_SM);
			
			createAttribute( imsldenvironments_environement_SM, "identifier", "env-"+tamsIds.get(sm.getTitle()));
			
			createElementwithAttribute( imsldenvironments_environement_SM, "imsld:title", sm.getTitle());
			
			Element imsldenvironments_service_SM = doc.createElement("imsld:service");
			imsldenvironments_environement_SM.appendChild(imsldenvironments_service_SM);
			
			createAttribute( imsldenvironments_service_SM, "identifier", "service-"+new BigInteger(130, random).toString(32));
			createAttribute( imsldenvironments_service_SM, "isvisible", "true");
			
			
			Element imsldenvironments_service_sent_mail = doc.createElement("imsld:send-mail");
			imsldenvironments_service_SM.appendChild(imsldenvironments_service_sent_mail);
			createAttribute( imsldenvironments_service_sent_mail, "select", "persons-in-role");
			
			createElementwithAttribute( imsldenvironments_service_sent_mail, "imsld:title", sm.getTitle());
			
			List<Role> recipients = sm.getRecipients();
			for(Role recipient: recipients){
				Element imsldenvironments_service_sent_email_data = doc.createElement("imsld:email-data");
				imsldenvironments_service_sent_mail.appendChild(imsldenvironments_service_sent_email_data);
				
				Element imsldenvironments_service_role_ref_SM = doc.createElement("imsld:role-ref");
				imsldenvironments_service_sent_email_data.appendChild(imsldenvironments_service_role_ref_SM);
				createAttribute( imsldenvironments_service_role_ref_SM, "ref", "role-"+roles.get(recipient.getText()));
			}
			
		}
	}
	
	
	private void createAnnounsementSEnvironment(Element imsldenvironments,UnitOfLearning uol) {
		List<AnnouncementService> announcementServices = toolAndMaterialService.getAnnouncementServiceByUoL(uol.getId());
		SecureRandom random = new SecureRandom();
		for(AnnouncementService as : announcementServices){
			if(!tamsIds.containsKey(as.getTitle())){
				String bi = new BigInteger(130, random).toString(32);
				tamsIds.put(as.getTitle(), bi);
			}
		}
		
		for(AnnouncementService as : announcementServices){
			
		
			Element imsldenvironments_environement_FS = doc.createElement("imsld:environment");
			imsldenvironments.appendChild(imsldenvironments_environement_FS);
			
			createAttribute(imsldenvironments_environement_FS, "identifier", "env-"+tamsIds.get(as.getTitle()));
			
			createElementwithAttribute( imsldenvironments_environement_FS, "imsld:title", as.getTitle());
			
			
			Element imsldenvironments_service_FS = doc.createElement("imsld:service");
			imsldenvironments_environement_FS.appendChild(imsldenvironments_service_FS);
			
			createAttribute( imsldenvironments_service_FS, "identifier", "service-"+new BigInteger(130, random).toString(32));
			createAttribute( imsldenvironments_service_FS, "isvisible", "true");
			
			
			
			Element imsldenvironments_service_conference_FS = doc.createElement("imsld:conference");
			imsldenvironments_service_FS.appendChild(imsldenvironments_service_conference_FS);
			
			createAttribute( imsldenvironments_service_conference_FS, "conference-type", "announcement");
			
			createElementwithAttribute( imsldenvironments_service_conference_FS, "imsld:title", as.getTitle());
			List<Role> participants = as.getParticipants();
			for(Role participant: participants){
				Element imsldenvironments_service_participant_FS = doc.createElement("imsld:participant");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_participant_FS);
				createAttribute( imsldenvironments_service_participant_FS, "role-ref", "role-"+roles.get(participant.getText()));
			}
			
			List<Role> observers = as.getObservers();
			for(Role observer : observers){
				Element imsldenvironments_service_observer_FS = doc.createElement("imsld:observer");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_observer_FS);
				createAttribute( imsldenvironments_service_observer_FS, "role-ref", "role-"+roles.get(observer.getText()));
			}
			
			if(as.getManager() != null){
				Element imsldenvironments_service_conference_manager_FS = doc.createElement("imsld:conference-manager");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_conference_manager_FS);
				createAttribute( imsldenvironments_service_conference_manager_FS, "role-ref", "role-"+roles.get(as.getManager().getText()));
			}
			if(as.getModerator() != null){
				Element imsldenvironments_service_moderator_FS = doc.createElement("imsld:moderator");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_moderator_FS);
				createAttribute( imsldenvironments_service_moderator_FS, "role-ref", "role-"+roles.get(as.getModerator()));
			}
			
			String descr = as.getDescription();
			FileUploadBean file = new FileUploadBean();
			file.setBytes(descr.getBytes());
			file.setName("AS-file-"+as.getTitle()+"-"+new BigInteger(130, random).toString(8)+".txt");
			file.setSize(descr.length());
			
			filesIds.put(file, "file-"+new BigInteger(130, random).toString(32));
			
			Element imsldsupportactivity_FS_item = doc.createElement("imsld:item");
			imsldenvironments_service_conference_FS.appendChild(imsldsupportactivity_FS_item);
			
			createAttribute(imsldsupportactivity_FS_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
			createAttribute(imsldsupportactivity_FS_item, "isvisible", "true");
			createAttribute(imsldsupportactivity_FS_item, "identifierref", filesIds.get(file));
			
			createElementwithAttribute( imsldsupportactivity_FS_item, "imsld:title", "AnnouncementService-Resource");
		}
	}
	
	private void createCSEnvironment(Element imsldenvironments,UnitOfLearning uol) {
		SecureRandom random = new SecureRandom();
		List<ChatService> chatServices = toolAndMaterialService.getChatServiceByUoL(uol.getId());
		for(ChatService cs : chatServices){
			if(!tamsIds.containsKey(cs.getTitle())){
				String bi = new BigInteger(130, random).toString(32);
				tamsIds.put(cs.getTitle(), bi);
			}
		}
		
		for(ChatService cs : chatServices){
			Element imsldenvironments_environement_FS = doc.createElement("imsld:environment");
			imsldenvironments.appendChild(imsldenvironments_environement_FS);
			
			createAttribute(imsldenvironments_environement_FS, "identifier", "env-"+tamsIds.get(cs.getTitle()));
			
			createElementwithAttribute( imsldenvironments_environement_FS, "imsld:title", cs.getTitle());
			
			
			Element imsldenvironments_service_FS = doc.createElement("imsld:service");
			imsldenvironments_environement_FS.appendChild(imsldenvironments_service_FS);
			
			createAttribute( imsldenvironments_service_FS, "identifier", "service-"+new BigInteger(130, random).toString(32));
			createAttribute( imsldenvironments_service_FS, "isvisible", "true");
			
			
			
			Element imsldenvironments_service_conference_FS = doc.createElement("imsld:conference");
			imsldenvironments_service_FS.appendChild(imsldenvironments_service_conference_FS);
			
			createAttribute( imsldenvironments_service_conference_FS, "conference-type", "synchronous");
			
			createElementwithAttribute( imsldenvironments_service_conference_FS, "imsld:title", cs.getTitle());
			 
			List<Role> participants = cs.getParticipants();
			for(Role participant : participants){
				Element imsldenvironments_service_participant_FS = doc.createElement("imsld:participant");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_participant_FS);
				createAttribute( imsldenvironments_service_participant_FS, "role-ref", "role-"+roles.get(participant.getText()));
			}
			
			List<Role> observers = cs.getObservers();
			for(Role observer : observers){
				Element imsldenvironments_service_observer_FS = doc.createElement("imsld:observer");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_observer_FS);
				createAttribute( imsldenvironments_service_observer_FS, "role-ref", "role-"+roles.get(observer.getText()));
			}
			if(cs.getManager() != null){
				Element imsldenvironments_service_conference_manager_FS = doc.createElement("imsld:conference-manager");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_conference_manager_FS);
				createAttribute( imsldenvironments_service_conference_manager_FS, "role-ref", "role-"+roles.get(cs.getManager().getText()));
			}
			
			if(cs.getModerator() != null){
				Element imsldenvironments_service_moderator_FS = doc.createElement("imsld:moderator");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_moderator_FS);
				createAttribute( imsldenvironments_service_moderator_FS, "role-ref", "role-"+roles.get(cs.getModerator().getText()));
			}
			Element imsldsupportactivity_FS_item = doc.createElement("imsld:item");
			imsldenvironments_service_conference_FS.appendChild(imsldsupportactivity_FS_item);
			
			String descr = cs.getDescription();
			FileUploadBean file = new FileUploadBean();
			file.setBytes(descr.getBytes());
			file.setName("CS-file-"+cs.getTitle()+"-"+new BigInteger(130, random).toString(8)+".txt");
			file.setSize(descr.length());
			if(!filesIds.containsKey(file)){
				filesIds.put(file, "file-"+new BigInteger(130, random).toString(32));
			}
			
			createAttribute( imsldsupportactivity_FS_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
			createAttribute( imsldsupportactivity_FS_item, "isvisible", "true");
			createAttribute( imsldsupportactivity_FS_item, "identifierref", filesIds.get(file));
			
			createElementwithAttribute( imsldsupportactivity_FS_item, "imsld:title", "ChatService-Resource");
		}
		
	}

	private void createFSEnvironment(Element imsldenvironments,UnitOfLearning uol) {
		
		List<ForumService> forumServices = toolAndMaterialService.getForumServicesByUoL(uol.getId());
		SecureRandom random = new SecureRandom();
		for(ForumService fs : forumServices){
			if(!tamsIds.containsKey(fs.getTitle())){
				String bi = new BigInteger(130, random).toString(32);
				tamsIds.put(fs.getTitle(), bi);
			}
		}
		
		for(ForumService fs : forumServices){
			
		
			Element imsldenvironments_environement_FS = doc.createElement("imsld:environment");
			imsldenvironments.appendChild(imsldenvironments_environement_FS);
			
			createAttribute(imsldenvironments_environement_FS, "identifier", "env-"+tamsIds.get(fs.getTitle()));
			
			createElementwithAttribute( imsldenvironments_environement_FS, "imsld:title", fs.getTitle());
			
			
			Element imsldenvironments_service_FS = doc.createElement("imsld:service");
			imsldenvironments_environement_FS.appendChild(imsldenvironments_service_FS);
			
			createAttribute( imsldenvironments_service_FS, "identifier", "service-"+new BigInteger(130, random).toString(32));
			createAttribute( imsldenvironments_service_FS, "isvisible", "true");
			
			
			
			Element imsldenvironments_service_conference_FS = doc.createElement("imsld:conference");
			imsldenvironments_service_FS.appendChild(imsldenvironments_service_conference_FS);
			
			createAttribute( imsldenvironments_service_conference_FS, "conference-type", "asynchronous");
			
			createElementwithAttribute( imsldenvironments_service_conference_FS, "imsld:title", fs.getTitle());
			List<Role> participants = fs.getParticipants();
			for(Role participant: participants){
				Element imsldenvironments_service_participant_FS = doc.createElement("imsld:participant");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_participant_FS);
				createAttribute( imsldenvironments_service_participant_FS, "role-ref", "role-"+roles.get(participant.getText()));
			}
			
			List<Role> observers = fs.getObservers();
			for(Role observer : observers){
				Element imsldenvironments_service_observer_FS = doc.createElement("imsld:observer");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_observer_FS);
				createAttribute( imsldenvironments_service_observer_FS, "role-ref", "role-"+roles.get(observer.getText()));
			}
			
			if(fs.getManager() != null){
				Element imsldenvironments_service_conference_manager_FS = doc.createElement("imsld:conference-manager");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_conference_manager_FS);
				createAttribute( imsldenvironments_service_conference_manager_FS, "role-ref", "role-"+roles.get(fs.getManager().getText()));
			}
			if(fs.getModerator() != null){
				Element imsldenvironments_service_moderator_FS = doc.createElement("imsld:moderator");
				imsldenvironments_service_conference_FS.appendChild(imsldenvironments_service_moderator_FS);
				createAttribute( imsldenvironments_service_moderator_FS, "role-ref", "role-"+roles.get(fs.getModerator().getText()));
			}
			
			String descr = fs.getDescription();
			FileUploadBean file = new FileUploadBean();
			file.setBytes(descr.getBytes());
			file.setName("FS-file-"+fs.getTitle()+"-"+new BigInteger(130, random).toString(8)+".txt");
			file.setSize(descr.length());
			
			filesIds.put(file, "file-"+new BigInteger(130, random).toString(32));
			
			Element imsldsupportactivity_FS_item = doc.createElement("imsld:item");
			imsldenvironments_service_conference_FS.appendChild(imsldsupportactivity_FS_item);
			
			createAttribute(imsldsupportactivity_FS_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
			createAttribute(imsldsupportactivity_FS_item, "isvisible", "true");
			createAttribute(imsldsupportactivity_FS_item, "identifierref", filesIds.get(file));
			
			createElementwithAttribute( imsldsupportactivity_FS_item, "imsld:title", "ForumService-Resource");
		
		}
	}

	private void createLOEnvironment(Element imsldenvironments,UnitOfLearning uol) {
		SecureRandom random = new SecureRandom();
		
		
		
		List<LearningObject> tams = toolAndMaterialService.getLearningObjectByUoL(uol.getId());
		for(LearningObject tam : tams){
			if(!tamsIds.containsKey(tam.getTitle())){
				String bi = new BigInteger(130, random).toString(32);
				tamsIds.put(tam.getTitle(), bi);
			}
		}
		
		for(LearningObject tam : tams){
			Element imsldenvironments_environement_LO = doc.createElement("imsld:environment");
			imsldenvironments.appendChild(imsldenvironments_environement_LO);
			
			createAttribute(imsldenvironments_environement_LO, "identifier", "env-"+tamsIds.get(tam.getTitle()));
			
			createElementwithAttribute(imsldenvironments_environement_LO, "imsld:title", tam.getTitle());
			
			Element imsldenvironments_LO = doc.createElement("imsld:learning-object");
			imsldenvironments_environement_LO.appendChild(imsldenvironments_LO);
			
			createAttribute(imsldenvironments_LO, "identifier", "lo-"+new BigInteger(130, random).toString(32));
			
			createElementwithAttribute(imsldenvironments_LO, "imsld:title", tam.getTitle());
			String descr = tam.getDescription();
			FileUploadBean file = new FileUploadBean();
			file.setBytes(descr.getBytes());
			file.setName("LO-file-"+tam.getTitle()+"-"+new BigInteger(130, random).toString(8)+".txt");
			file.setSize(descr.length());
			if(!filesIds.containsKey(file)){
				filesIds.put(file, "file-"+new BigInteger(130, random).toString(32));
			}
			Element imsldsupportactivity_LO_item = doc.createElement("imsld:item");
			imsldenvironments_LO.appendChild(imsldsupportactivity_LO_item);
			
			createAttribute(imsldsupportactivity_LO_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
			createAttribute(imsldsupportactivity_LO_item, "isvisible", "true");
			createAttribute(imsldsupportactivity_LO_item, "identifierref", filesIds.get(file));
			
			createElementwithAttribute(imsldsupportactivity_LO_item, "imsld:title", "LearningObject-Resource");
		}
		
		
	}

	private void createSupportActivityXML(Element imsldactivities,UnitOfLearning uol) {
		
		SecureRandom random = new SecureRandom();
		List<Activity> activities = uol.getActivity();
		
		for(Activity activity : activities){
			if(activity instanceof SupportActivity){
				String bi = new BigInteger(130, random).toString(32);
				Element imsldsupportactivity = doc.createElement("imsld:support-activity");
				imsldactivities.appendChild(imsldsupportactivity);
				createAttribute(imsldsupportactivity, "identifier", "prop-"+bi);
				actSupportIds.put(activity.getActivityGraphId(), "prop-"+bi);
				createAttribute(imsldsupportactivity, "isvisible", String.valueOf(activity.isVisible()));
				
				createElementwithAttribute(imsldsupportactivity, "imsld:title", activity.getActivityGraphId());
				List<Role> activityRoles = ((SupportActivity) activity).getSupportedRoles();
				for(Role role : activityRoles ){
					if(roles.containsKey(role.getText())){
						Element imsldsupportactivity_environment_ref = doc.createElement("imsld:role-ref");
						imsldsupportactivity.appendChild(imsldsupportactivity_environment_ref);
						createAttribute(imsldsupportactivity_environment_ref, "ref", "role-"+roles.get(role.getText()));
					}
				}
				
				List<ToolAndMaterial> tams = activity.getTams();
				for(ToolAndMaterial tam : tams){
					Element imsldsupportactivity_environment_ref = doc.createElement("imsld:environment-ref");
					imsldsupportactivity.appendChild(imsldsupportactivity_environment_ref);
					if(tamsIds.containsKey(tam.getTitle())){
						createAttribute(imsldsupportactivity_environment_ref, "ref", "env-"+tamsIds.get(tam.getTitle()));
					}else{
						String refEnv = new BigInteger(130, random).toString(32);
						createAttribute(imsldsupportactivity_environment_ref, "ref", "env-"+refEnv);
						tamsIds.put(tam.getTitle(), refEnv);
					}
				}
				//imsld:environment-ref
				Element imsldsupportactivity_description = doc.createElement("imsld:activity-description");
				imsldsupportactivity.appendChild(imsldsupportactivity_description);
				List<FileUploadBean> files = activity.getFiles();
//				Element imsldsupportactivity_item = doc.createElement("imsld:item");
//				imsldsupportactivity_description.appendChild(imsldsupportactivity_item);
				for(FileUploadBean file : files){
					if(file.getResourceType().equals(ResourceType.SADESCRIPTION)){
						Element imsldsupportactivity_description_item = doc.createElement("imsld:item");
						imsldsupportactivity_description.appendChild(imsldsupportactivity_description_item);
						createAttribute(imsldsupportactivity_description_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
						createAttribute(imsldsupportactivity_description_item, "isvisible", "true");
						String fileIdent = new BigInteger(130, random).toString(32);
						createAttribute(imsldsupportactivity_description_item, "identifierref", "file-"+fileIdent);
						if(!fileIds.containsKey(fileIdent)){
							fileIds.put("file-"+fileIdent, file.getName());
						}
						createElementwithAttribute(imsldsupportactivity_description_item, "imsld:title", file.getName());
						
					}
				}
				
				if(activity.getFinishingActivity().equals(FinishingActivity.NONE)){
					Element imsldsupportactivity_complete_activity = doc.createElement("imsld:complete-activity");
					imsldsupportactivity.appendChild(imsldsupportactivity_complete_activity);
				}else if(activity.getFinishingActivity().equals(FinishingActivity.TIMELIMIT)){
					Element imsldsupportactivity_complete_activity = doc.createElement("imsld:complete-activity");
					imsldsupportactivity.appendChild(imsldsupportactivity_complete_activity);
					
					Element imsldlearningactivity_time_limit = doc.createElement("imsld:time-limit");
					imsldlearningactivity_time_limit.appendChild(doc.createTextNode("P1Y111M10DT10H10M10S"));
					imsldsupportactivity_complete_activity.appendChild(imsldlearningactivity_time_limit);
				}else{
					Element imsldsupportactivity_complete_activity = doc.createElement("imsld:complete-activity");
					imsldsupportactivity.appendChild(imsldsupportactivity_complete_activity);
					
					Element imsldlearningactivity_time_limit = doc.createElement("imsld:user-choice");
					imsldsupportactivity_complete_activity.appendChild(imsldlearningactivity_time_limit);
				}
				
				
			}
		}
		
	}

	private void createLearningActivityXML(Element imsldactivities,UnitOfLearning uol) {
		
		SecureRandom random = new SecureRandom();
		List<Activity> activities = uol.getActivity();
		for(Activity activity : activities){
			
			if(activity instanceof LearningActivity){
			
				Element imsldlearningactivity = doc.createElement("imsld:learning-activity");
				imsldactivities.appendChild(imsldlearningactivity);
				String bi = new BigInteger(130, random).toString(32);
				createAttribute(imsldlearningactivity, "identifier", "prop-"+bi);
				actLearningIds.put(activity.getActivityGraphId(), "prop-"+bi);
				createAttribute(imsldlearningactivity, "isvisible", "true");
				
				createElementwithAttribute(imsldlearningactivity, "imsld:title", activity.getActivityGraphId());
				List<FileUploadBean> files = activity.getFiles();
				for(FileUploadBean file : files){
					if(file.getResourceType().equals(ResourceType.LAOBJECTIVE)){
						Element imsldlearningactivity_learningobjectives = doc.createElement("imsld:learning-objectives");
						imsldlearningactivity.appendChild(imsldlearningactivity_learningobjectives);
						
						createElementwithAttribute(imsldlearningactivity_learningobjectives, "imsld:title", "Learning Objectives Resources");
						
						Element imsldlearningactivity_learningobjectives_item = doc.createElement("imsld:item");
						imsldlearningactivity_learningobjectives.appendChild(imsldlearningactivity_learningobjectives_item);
						
						createAttribute(imsldlearningactivity_learningobjectives_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
						String fileIdent = new BigInteger(130, random).toString(32);
						createAttribute(imsldlearningactivity_learningobjectives_item, "identifierref", "file-"+fileIdent);
						if(!fileIds.containsKey(fileIdent)){
							fileIds.put("file-"+fileIdent, file.getName());
						}
						createAttribute(imsldlearningactivity_learningobjectives_item, "isvisible", "true");
						
						createElementwithAttribute(imsldlearningactivity_learningobjectives_item, "imsld:title", file.getName());
						
					}else if(file.getResourceType().equals(ResourceType.LAPREREQUISITES)){
						Element imsldlearningactivity_prerequisites = doc.createElement("imsld:prerequisites");
						imsldlearningactivity.appendChild(imsldlearningactivity_prerequisites);
						
						createElementwithAttribute(imsldlearningactivity_prerequisites, "imsld:title", "Prerequisites Resources");
						
						Element imsldlearningactivity_prerequisites_item = doc.createElement("imsld:item");
						imsldlearningactivity_prerequisites.appendChild(imsldlearningactivity_prerequisites_item);
						
						createAttribute(imsldlearningactivity_prerequisites_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
						createAttribute(imsldlearningactivity_prerequisites_item, "isvisible", "true");
						String fileIdent = new BigInteger(130, random).toString(32);
						createAttribute(imsldlearningactivity_prerequisites_item, "identifierref", "file-"+fileIdent);
						if(!fileIds.containsKey(fileIdent)){
							fileIds.put("file-"+fileIdent, file.getName());
						}
						createElementwithAttribute(imsldlearningactivity_prerequisites_item, "imsld:title", file.getName());
					}
				}
				

				List<ToolAndMaterial> tams = activity.getTams();
				for(ToolAndMaterial tam : tams){
					Element imsldlearningactivity_environment_ref = doc.createElement("imsld:environment-ref");
					imsldlearningactivity.appendChild(imsldlearningactivity_environment_ref);
					String fileIdent = new BigInteger(130, random).toString(32);
					createAttribute(imsldlearningactivity_environment_ref, "ref", "env-"+fileIdent);
					if(!tamsIds.containsKey(tam.getTitle())){
						tamsIds.put(tam.getTitle(), fileIdent);
					}
				}
				
				String activityDescription ="";
				if(!StringUtils.isEmpty(activity.getDescription())){
					activityDescription = activity.getDescription();
				}else{
					activityDescription = "Activity Description";
				}
				Element imsldlearningactivity_description = doc.createElement("imsld:activity-description");
				imsldlearningactivity.appendChild(imsldlearningactivity_description);
				
				createElementwithAttribute(imsldlearningactivity_description, "imsld:title", activityDescription);
				
				for(FileUploadBean file : files){
					if(file.getResourceType().equals(ResourceType.LADESCRIPTION)){
						Element imsldlearningactivity_description_item = doc.createElement("imsld:item");
						imsldlearningactivity_description.appendChild(imsldlearningactivity_description_item);
						createAttribute(imsldlearningactivity_description_item, "identifier", "prop-"+new BigInteger(130, random).toString(32));
						createAttribute(imsldlearningactivity_description_item, "isvisible", "true");
						String fileIdent = new BigInteger(130, random).toString(32);
						createAttribute(imsldlearningactivity_description_item, "identifierref", "file-"+fileIdent);
						if(!fileIds.containsKey(fileIdent)){
							fileIds.put("file-"+fileIdent, file.getName());
						}
						createElementwithAttribute(imsldlearningactivity_description_item, "imsld:title", file.getName());
						
					}
				}
				
				if(activity.getFinishingActivity().equals(FinishingActivity.NONE)){
					Element imsldlearningactivity_complete_activity = doc.createElement("imsld:complete-activity");
					imsldlearningactivity.appendChild(imsldlearningactivity_complete_activity);
				}else if(activity.getFinishingActivity().equals(FinishingActivity.TIMELIMIT)){
					Element imsldlearningactivity_complete_activity = doc.createElement("imsld:complete-activity");
					imsldlearningactivity.appendChild(imsldlearningactivity_complete_activity);
					
					Element imsldlearningactivity_time_limit = doc.createElement("imsld:time-limit");
					imsldlearningactivity_time_limit.appendChild(doc.createTextNode("P1Y111M10DT10H10M10S"));
					imsldlearningactivity_complete_activity.appendChild(imsldlearningactivity_time_limit);
				}else{
					Element imsldlearningactivity_complete_activity = doc.createElement("imsld:complete-activity");
					imsldlearningactivity.appendChild(imsldlearningactivity_complete_activity);
					
					Element imsldlearningactivity_time_limit = doc.createElement("imsld:user-choice");
					imsldlearningactivity_complete_activity.appendChild(imsldlearningactivity_time_limit);
				}
				
//				Element imsldlearningactivity_on_completion = doc.createElement("imsld:on-completion");
//				imsldlearningactivity.appendChild(imsldlearningactivity_on_completion);
//				
//				
//				Element imsldlearningactivity_on_completionfeedbackdescription = doc.createElement("imsld:feedback-description");
//				imsldlearningactivity_on_completion.appendChild(imsldlearningactivity_on_completionfeedbackdescription);
//				
//				createElementwithAttribute(imsldlearningactivity_on_completionfeedbackdescription, "imsld:title", "Feedback Title");
//				
//				Element imsldlearningactivity_feedback_item = doc.createElement("imsld:item");
//				imsldlearningactivity_on_completionfeedbackdescription.appendChild(imsldlearningactivity_feedback_item);
//				
//				createAttribute(imsldlearningactivity_feedback_item, "identifier", "prop-03ea09c3-55cc-4b67-91c9-bddace692203");
//				createAttribute(imsldlearningactivity_feedback_item, "isvisible", "true");
//				createAttribute(imsldlearningactivity_feedback_item, "identifierref", "file-44198170-5");
//				
//				createElementwithAttribute(imsldlearningactivity_feedback_item, "imsld:title", "Feedback Description Title");
			}
			
		}
	}

	private void createRolesXML(Element imsldcomponents,UnitOfLearning uol) {
		Element imsldroles = doc.createElement("imsld:roles");
		imsldcomponents.appendChild(imsldroles);
		SecureRandom random = new SecureRandom();

		//imsldroles.appendChild(imsldlearner);
		List<Role> learners = roleService.getLearnerRolesByUoL(uol.getId());
		for(Role role : learners){
			String bi = new BigInteger(130, random).toString(32);
			Element imsldlearner = doc.createElement("imsld:learner");
			imsldroles.appendChild(imsldlearner);
			createAttribute(imsldlearner, "identifier", "role-"+bi);
			createElementwithAttribute(imsldlearner, "imsld:title", role.getText());
			if(!roles.containsKey(role.getText())){
				roles.put(role.getText(), bi);
			}
			
		}
		List<Role> staffs = roleService.getStaffRolesByUoL(uol.getId());
		for(Role role : staffs){
			String bi = new BigInteger(130, random).toString(32);
			Element imsldstaff = doc.createElement("imsld:staff");
			imsldroles.appendChild(imsldstaff);
			createAttribute(imsldstaff, "identifier", "role-"+bi);
			createElementwithAttribute(imsldstaff, "imsld:title", role.getText());
			if(!roles.containsKey(role.getText())){
				roles.put(role.getText(), bi);
			}
		}
		
		
		//createElementwithAttribute(imsldstaff, "imsld:title", "Staff");
	}

	private void createAddonXML(Element imsldcomponents,UnitOfLearning uol) {
		SecureRandom random = new SecureRandom();
		
		Element imsldproperties = doc.createElement("imsld:properties");
		imsldcomponents.appendChild(imsldproperties);
		List<Addon> addons = addonService.getAddonsByUoL(uol.getId());
		
		for(Addon addon : addons){
			Element imsldproperty_group = doc.createElement("imsld:property-group");
			imsldproperties.appendChild(imsldproperty_group);
			createAttribute(imsldproperty_group, "identifier", "propgroup-"+new BigInteger(130, random).toString(32));
		
		
			createElementwithAttribute(imsldproperty_group, "imsld:title", addon.getTitle());
			String bi = new BigInteger(130, random).toString(32);
			Element imsldproperty_group_ref = doc.createElement("imsld:property-ref");
			imsldproperty_group.appendChild(imsldproperty_group_ref);
			createAttribute(imsldproperty_group_ref, "ref", "prop-"+bi);
			
			Element imsldlocpers_property = doc.createElement("imsld:locpers-property");
			imsldproperties.appendChild(imsldlocpers_property);
			createAttribute(imsldlocpers_property, "identifier", "prop-"+bi);
			
			createElementwithAttribute(imsldlocpers_property, "imsld:title", addon.getTitle()+" - Text");
			
			Element imsldlocpers_dataType = doc.createElement("imsld:datatype");
			imsldlocpers_property.appendChild(imsldlocpers_dataType);
			createAttribute(imsldlocpers_dataType, "datatype", "text");
		}
		
	}
	
	
	public void createElement(Element toBeAttached, String attri){
		Element imsldlearningactivity_description_title = doc.createElement(attri);
		toBeAttached.appendChild(imsldlearningactivity_description_title);
	}
	
	public void createElementwithAttribute(Element toBeAttached, String attri, String value){
		Element imsldlearningactivity_description_title = doc.createElement(attri);
		imsldlearningactivity_description_title.appendChild(doc.createTextNode(value));
		toBeAttached.appendChild(imsldlearningactivity_description_title);
	}
	
	public void createAttribute(Element toBeAttached, String attr, String value){
		Attr imsldlearning_designidentifier = doc.createAttribute(attr);
		imsldlearning_designidentifier.setValue(value);
		toBeAttached.setAttributeNode(imsldlearning_designidentifier);
	}

	public IUnitOfLearningService getUnitOfLearningService() {
		return unitOfLearningService;
	}
	@Resource(name="unitOfLearningService")
	public void setUnitOfLearningService(
			IUnitOfLearningService unitOfLearningService) {
		this.unitOfLearningService = unitOfLearningService;
	}
	public IGraphService getGraphService() {
		return graphService;
	}
	@Resource(name="graphService")
	public void setGraphService(IGraphService graphService) {
		this.graphService = graphService;
	}

	public IFileUploadBeanService getFileUploadBeanService() {
		return fileUploadBeanService;
	}
	@Resource(name="fileUploadBeanService")
	public void setFileUploadBeanService(
			IFileUploadBeanService fileUploadBeanService) {
		this.fileUploadBeanService = fileUploadBeanService;
	}
	public IRoleService getRoleService() {
		return roleService;
	}
	@Resource(name="roleService")
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}
	public IAddonService getAddonService() {
		return addonService;
	}
	@Resource(name="addonService")
	public void setAddonService(IAddonService addonService) {
		this.addonService = addonService;
	}
	public IToolAndMaterialService getToolAndMaterialService() {
		return toolAndMaterialService;
	}
	@Resource(name="toolAndMaterialService")
	public void setToolAndMaterialService(
			IToolAndMaterialService toolAndMaterialService) {
		this.toolAndMaterialService = toolAndMaterialService;
	}

	public IActivityService getActivityService() {
		return activityService;
	}
	@Resource(name="activityService")
	public void setActivityService(IActivityService activityService) {
		this.activityService = activityService;
	}

}
